package
{
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import mx.core.BitmapAsset;
	import mx.core.UIComponent;
	
	public class BitmapRenderer extends UIComponent
	{
		[Bindable]
		public var numBitmaps:uint = 1000;
		
		private const canvasBitmap:BitmapAsset = new BitmapAsset();
		private var canvas:BitmapData;
		
		private const bitmaps:Vector.<BitmapData> = new Vector.<BitmapData>(numBitmaps, true);
		
		private var canvasRect:Rectangle;
		
		public function BitmapRenderer()
		{
			super();
			
			addEventListener(Event.ADDED_TO_STAGE, addedToStage);
		}
		
		private function addedToStage(event:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, addedToStage);
			addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
		
			canvasRect = new Rectangle(0, 0, stage.width, stage.height);
			canvas = new BitmapData(stage.width, stage.height);			
			canvas.fillRect(canvasRect, 0xFFFFFF);
			canvasBitmap.bitmapData = canvas;
			canvasBitmap.x = 0;
			canvasBitmap.y = 0;
			addChild(canvasBitmap);
			
			const rect:Rectangle = new Rectangle();
			for (var i:int = 0; i < numBitmaps; i++)
			{
				const data:BitmapData = new BitmapData(randomNum(10, 50), randomNum(10, 50));
				rect.width = data.width;
				rect.height = data.height;
				data.fillRect(rect, randomColor());
				bitmaps[i] = data;
			}
			
			addEventListener(Event.ENTER_FRAME, update);
		}
		
		private function removedFromStage(event:Event):void
		{
			removeEventListener(Event.ENTER_FRAME, update);
			removeEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
			addEventListener(Event.ADDED_TO_STAGE, addedToStage);
			
			removeChild(canvasBitmap);
		}
		
		private function update(event:Event):void
		{
			canvas.fillRect(canvasRect, 0xFFFFFF);

			const targetRect:Rectangle = new Rectangle();
			const targetPoint:Point = new Point();
			for each (var bitmap:BitmapData in bitmaps)
			{
				targetPoint.x = randomNum(0, stage.width - bitmap.width);
				targetPoint.y = randomNum(0, stage.height - bitmap.height);
				targetRect.width = bitmap.width;
				targetRect.height = bitmap.height;
				canvas.copyPixels(bitmap, targetRect, targetPoint);
			}
		}

		private function randomColor():uint
		{
			return uint(Math.floor(Math.random() * 4294967295));
		}
		
		private function randomNum(min:uint, max:uint):uint 
		{
			return Math.round(Math.random() * (max - min)) + min;
		}
	}
}